﻿
using System.Security.Cryptography;


namespace YY.Admin.Application.Service
{
    public class SysAuthService : ISysAuthService
    {
        private SysUser? _currentUser;
        public SysUser? CurrentUser => _currentUser;
        public event EventHandler<SysUser?>? UserChanged;
        private readonly ISqlSugarDbContext _dbContext;
        public SysAuthService(ISqlSugarDbContext dbContext) {
            _dbContext=dbContext;
        }
        public async Task<LoginResponse> LoginAsync(LoginRequest request)
        {
            try
            {
                // 判断密码错误次数（缓存30分钟）
                var keyPasswordErrorTimes = $"{CacheConst.KeyPasswordErrorTimes}{request.Username}";

                var qweqwe=await _dbContext.Db.Queryable<SysUser>().ToListAsync();
                // 这里你可以调用数据库验证
                // 示例：简单的用户名密码验证
                if (request.Username == "admin" && request.Password == "123456")
                {
                    _currentUser = new SysUser
                    {
                        Id = 1,
                        RealName = request.Username,
                        Email = "admin@example.com",
                        //Role = "Administrator",
                        //CreatedAt = DateTime.Now.AddYears(-1),
                        //LastLoginAt = DateTime.Now,
                        //IsActive = true
                    };

                    UserChanged?.Invoke(this, _currentUser);

                    return new LoginResponse
                    {
                        Success = true,
                        Message = "登录成功",
                        User = _currentUser,
                        Token = GenerateToken()
                    };
                }
                else
                {
                    return new LoginResponse
                    {
                        Success = false,
                        Message = "用户名或密码错误"
                    };
                }
            }
            catch (Exception ex)
            {
                return new LoginResponse
                {
                    Success = false,
                    Message = $"登录失败：{ex.Message}"
                };
            }
        }

        public async Task LogoutAsync()
        {
            await Task.Delay(100);
            _currentUser = null;
            UserChanged?.Invoke(this, null);
        }

        public async Task<bool> IsAuthenticatedAsync()
        {
            await Task.Delay(50);
            return _currentUser != null;
        }

        private string GenerateToken()
        {
            var bytes = new byte[32];
            using var rng = RandomNumberGenerator.Create();
            rng.GetBytes(bytes);
            return Convert.ToBase64String(bytes);
        }
    }
}
